package vip.youngboy.liquibasedemo.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import vip.youngboy.liquibasedemo.domain.User;
import vip.youngboy.liquibasedemo.repository.UserRepository;
import vip.youngboy.liquibasedemo.util.BeanPropertysUtil;

import java.util.Optional;

@RestController
@RequestMapping("/api/user")
public class UserResource {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/findbyid/{id}")
    public User findUserById(@PathVariable String id) {
        return userRepository.findById(id).orElseThrow(() -> new RuntimeException("找不到用户"));
    }

    @GetMapping("/findall")
    public Iterable<User> findAll() {
        return userRepository.findAll();
    }

    @PostMapping("/adduser")
    public User addUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @PutMapping("/updateuser")
    public User updateUser(@RequestBody User user) {
        Assert.notNull(user.getId(), "用户id不能为空");
        Optional<User> ouser = userRepository.findById(user.getId());
        User existUser = ouser.orElseThrow(() -> new RuntimeException("找不到用户"));
        //复制不为空的属性
        BeanPropertysUtil.copyNonNullProperties(user, existUser);
        //重新保存用户
        return userRepository.save(user);
    }

    /**
     * 删除
     *
     * @param id 用户id
     * @return 204
     */
    @DeleteMapping("/deleteuser/{id}")
    public ResponseEntity deleteUser(@PathVariable String id) {
        userRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }


}
